package com.ssm.service.serviceImpl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ssm.entity.Student;
import com.ssm.entity.StudentExample;
import com.ssm.mapper.ClassMapper;
import com.ssm.mapper.StudentMapper;
import com.ssm.service.StudentService;
import com.ssm.utils.PageResult;
import com.ssm.vo.StudentVo;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
    private final StudentMapper studentMapper;
    private final ClassMapper classMapper;

    public StudentServiceImpl(StudentMapper studentMapper, ClassMapper classMapper) {
        this.studentMapper = studentMapper;
        this.classMapper = classMapper;
    }

    @Override
    public List<Student> findAll() {
        List<Student> students = studentMapper.selectByExample(null);
        if (students != null && !students.isEmpty()) {
            for (Student student : students) {
                student.setCname(classMapper.selectByPrimaryKey(student.getCid()).getCname());
            }
            return students;
        }
        return Collections.emptyList();
    }

    @Override
    public PageResult<Student> findByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<Student> studentPage = (Page<Student>) this.findAll();
        if (studentPage != null) {
            return new PageResult<>(studentPage.getResult(), studentPage.getTotal());
        }
        return new PageResult<>(Collections.emptyList(), 0L);
    }

    @Override
    public PageResult<Student> conditionFindByPage(Integer page, Integer pageSize, StudentVo studentVo) {

        PageHelper.startPage(page, pageSize);
        StudentExample studentExample = new StudentExample();
        StudentExample.Criteria criteria = studentExample.createCriteria();
        if(StrUtil.isNotBlank(studentVo.getName())){
            criteria.andNameLike("%" + studentVo.getName() + "%");
        }
        if(StrUtil.isNotBlank(studentVo.getAddr())){
            criteria.andAddrLike("%" + studentVo.getAddr() + "%");
        }
        if(studentVo.getCid() != null&&studentVo.getCid() != 0){
            criteria.andCidEqualTo(studentVo.getCid());
        }
        Page<Student> studentPage = (Page<Student>) studentMapper.selectByExample(studentExample);
        if (studentPage != null) {
            return new PageResult<>(studentPage.getResult(), studentPage.getTotal());
        }
        return new PageResult<>(Collections.emptyList(), 0L);
    }

    @Override
    public boolean addStudent(Student student) {
        student.setCname(classMapper.selectByPrimaryKey(student.getCid()).getCname());
        return studentMapper.insert(student) > 0;
    }
}
